//
//  KKWebViewController.m
//  webIOS
//
//  Created by Canny on 2018/10/19.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "KKWebViewController.h"
#import "WKWebView+AccessoryHiding.h"
#import "ExceptionView.h"
#import "AppDelegate.h"
#import <JavaScriptCore/JavaScriptCore.h>


#define HEIGHT_IPHoneX   0
@interface KKWebViewController  ()<WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) WKWebView *wkWebview;
@property(nonatomic, strong)ExceptionView * exceptionView;
@property(nonatomic,strong)NSString * updateURL;

@property(nonatomic,strong) NSString *currentURL;
@end

@implementation KKWebViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"APP_CCClose" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"APP_OOOpen" object:nil];

    
}

#pragma mark-锁屏
-(void)APP_CCClose{
    
    //设置JS

    NSString *inputValueJS = @"javascript:iosMethodClose()";
    //执行JS
    [self.wkWebview evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];

}

#pragma ------- 开屏幕
-(void)APP_OOOpen{
//    [self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
//mWebView.evaluateJavascript("javascript:iosMethod()")
//    mWebView.loadUrl("javascript:choiceTeam('"+split[0]+"','"+split[1] +"','"+split[2]+"','"+split[3]+"','"+split[4]+"','"+split[5]+"','"+split[6]+"')");
    
//    if ([_currentURL containsString:@"#/kline"]||[_currentURL containsString:@"zh-tv-chart"]) {
        //设置JS
    [self performSelector:@selector(iosMethodOpen) withObject:nil afterDelay:1];
//        NSString *inputValueJS = @"javascript:iosMethodOpen()";
//        //执行JS
//        [self.wkWebview evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//            NSLog(@"value: %@ error: %@", response, error);
//        }];
//    }


}

-(void)iosMethodOpen{
    NSString *inputValueJS = @"javascript:iosMethodOpen()";
    //执行JS
    [self.wkWebview evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
    [self prefersStatusBarHidden];
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    if (_strTitle) {
        self.title=_strTitle;
    }
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView*)scrollView{ // 实现代理方法， step 3
    return nil;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) { //确认
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.updateURL]];
    }
    [self exitApp];
}
- (void)exitApp{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:0.4f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    
    
}
//检测更新弹框
-(void)openUpdate:(NSString *)url{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发现新版本，请更新！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate=self;
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(APP_CCClose) name:@"APP_CCClose" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(APP_OOOpen) name:@"APP_OOOpen" object:nil];


    
    NSString * URL = [NSString stringWithFormat:@"http://api.3iex.com/normal/clientUpdate"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    __weak __typeof(self)wself = self;

    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:@{@"type":@"ios",@"version":app_Version} SuccessBlock:^(id  _Nonnull responseObject) {

        NSDictionary * dic = responseObject;

        if ([dic[@"code"] integerValue]==0) {
            if ([dic[@"data"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary * dicc = dic[@"data"];
                if([[dicc allKeys] containsObject:@"is_update"]&&[[dicc allKeys] containsObject:@"update_url"])

                {
                    NSString * is_update = [NSString stringWithFormat:@"%@",dicc[@"is_update"]];

                    NSString * update_url= [NSString stringWithFormat:@"%@",dicc[@"update_url"]];

                    if ([is_update integerValue]>0) {
                        if (update_url.length>0) {

                            if (![update_url containsString:@"http"]) {
                                update_url = [NSString stringWithFormat:@"https://%@",update_url];
                            }
                            wself.updateURL = update_url;
                            [wself openUpdate:update_url];
                        }
                    }
                }
            }
        }




    } FailureBlock:^(id  _Nonnull error) {





    }];
    
    
    if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        self.navigationController.navigationBar.hidden=YES;
    }else{
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        self.navigationController.navigationBar.hidden=YES;
    }
    
    
    [super viewWillAppear:animated];
    self.wkWebview.scrollView.delegate = self; // 注册代理， step 2

    self.wkWebview.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag; // 当拖动时移除键盘
    
    //TODO:加载
    [self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
    //TODO:kvo监听，获得页面title和加载进度值
    [self.wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    
//    [BKIndicationView showInView:self.view];

    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}


- (WKWebView *)wkWebview
{
    if (_wkWebview == nil)
    {
        _wkWebview = [[WKWebView alloc]init];
        _wkWebview.UIDelegate = self;
        _wkWebview.navigationDelegate = self;
        _wkWebview.backgroundColor = [UIColor whiteColor];
        _wkWebview.hackishlyHidesInputAccessoryView = YES;
    }
    return _wkWebview;
}


-(void)createUI{
    
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.wkWebview];
    
    if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
        self.wkWebview.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT+HEIGHT_IPHoneX);

    }else{
        self.wkWebview.frame=CGRectMake(0, -20, G_SCREENWIDTH, G_SCREENHEIGHT+20);

    }
    
    
    self.wkWebview.UIDelegate = self;
    self.wkWebview.navigationDelegate = self;
//    self.wkWebview.showsVerticalScrollIndicator = NO;
    
}

//1.转换编码
-(NSURL *)GetNSURLWithURL:(NSString *)sUrl{
    NSURL *url = [NSURL URLWithString:sUrl];
    return url;
}

//2.除去空格
+(NSString *)returnFormatString:(NSString *)str
{
    return [str stringByReplacingOccurrencesOfString:@" "withString:@" "];
}

/*浏览器后退*/
- (void)clickGoBackBtn{
    if(self.wkWebview.canGoBack){
        [self.wkWebview goBack];
    }
}

/*浏览器前进*/
- (void)clickGoForwardBtn{
    if(self.wkWebview.canGoForward){
        [self.wkWebview goForward];
    }
}

#pragma mark - UIWebViewDelegate代理方法
#pragma mark 开始加载
//是否允许加载网页，也可获取js要打开的url，通过截取此url可与js交互
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
{
    
    return YES;
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSString *currentURL = [NSString stringWithFormat:@"%@",webView.URL.absoluteString];
    _currentURL = currentURL;
//    http://192.168.3.9:8080/#/kline?counterparty=BTCUSDT&base_symbol=BTC&baseId=1&quote_symbol=USDT&quoteId=3&pairId=2
    
    
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
    NSString *currentURL = [NSString stringWithFormat:@"%@",webView.URL.absoluteString];
    _currentURL = currentURL;
    
}


//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//
//    NSLog(@"%@",navigationAction.request.URL.absoluteString);
//
//
//
//
//}

// 在收到响应开始加载后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    completionHandler();
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    WS(weakSelf);
    
    [BKIndicationView dismiss];
    NSString *currentURL = [NSString stringWithFormat:@"%@",webView.URL.absoluteString];
    _currentURL = currentURL;
//    JSContext *contest =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//
//    //    choiceTeam
//
//    // 打印异常,由于JS的异常信息是不会在OC中被直接打印的,所以我们在这里添加打印异常信息,
//    contest.exceptionHandler =
//    ^(JSContext *context, JSValue *exceptionValue)
//    {
//        context.exception = exceptionValue;
//    };
//
//    contest[@"close"] =
//    ^()
//    {
//
//
//
//    };
  
    
}

-(void)JSBack{
    
    NSLog(@"---------88888---------");
    
}

//网页加载错误
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
    NSLog(@"网页由于某些原因加载失败");
    NSString *currentURL = [NSString stringWithFormat:@"%@",webView.URL.absoluteString];
    _currentURL = currentURL;
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [BKIndicationView dismiss];
    [self showAgainLoad];
}

-(void)showAgainLoad{
    
    __weak __typeof__ (self) wself = self;

    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络错误，请重试！" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        

        [wself loadApi];
        
    }]];
    
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)loadApi{
    //TODO:加载
    [self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
//    [BKIndicationView showInView:self.view];
}

#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
}
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
//    NSLog(@"receive");
//
//    [BKIndicationView dismiss];
//
//}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败,失败原因:%@",[error description]);
    [BKIndicationView dismiss];
    
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"网页加载内容进程终止");
    [BKIndicationView dismiss];
}

#pragma mark 移除观察者
- (void)dealloc
{
    [self.wkWebview removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//键盘弹出后将视图向上移动
-(void)keyboardWillShow:(NSNotification *)note{
    
    NSDictionary * info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    NSTimeInterval animationDuration = 0.00f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    if (keyboardSize.height>400) {
        
        if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
            self.wkWebview.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT  - 400+HEIGHT_IPHoneX);
            
        }else{
            self.wkWebview.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT - 400);
            
        }
        NSLog(@"web的高度----%f",G_SCREENHEIGHT - 400);
    }else{
        
        if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
            self.wkWebview.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT - keyboardSize.height+HEIGHT_IPHoneX);
            
        }else{
            self.wkWebview.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT - keyboardSize.height);
            
        }
        
        
        NSLog(@"web的高度----%f",G_SCREENHEIGHT - keyboardSize.height);
    }
    

    NSLog(@"---键盘的高度---%f",keyboardSize.height);
    
    [UIView commitAnimations];

    
}


//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note{
    
    NSTimeInterval animationDuration = 0.30f;
    
    [UIView beginAnimations:@"ResizeView" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
 
    
    if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
        self.wkWebview.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT+HEIGHT_IPHoneX);
        
    }else{
        self.wkWebview.frame=CGRectMake(0, -20, G_SCREENWIDTH, G_SCREENHEIGHT+20);
        
    }
    [UIView commitAnimations];
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *requestString = navigationAction.request.URL.absoluteString;
    _currentURL = requestString;
//    NSLog(@"------------%lu",(unsigned long)webView.backForwardList.backList.count);
    
////    if (webView.backForwardList.backList.count == 0) {
////        <#statements#>
////    }
//    NSURLRequest *request = navigationAction.request;
//    if (navigationAction.navigationType==WKNavigationTypeBackForward) { //判断是返回类型
//
//
//
//        //        if (webView.backForwardList.backList.count == 0) { //得到栈里面的list
////            [self backToView];
////        }
//    }
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
    

    
}





@end


















